package 预科0104_Q2_Q3;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/* 使用线程池将一个目录中的所有内容拷贝到另外一个目录中，包含子目录中的内容。 */


public class DirsCopyTest {
	public static void main(String[] args) {
		ExecutorService es= Executors.newFixedThreadPool(10);
		es.execute(new Runnable() {

			@Override
			public void run() {
				try {
					dirsCopy("D:/dircopy","D:/dircopy_2");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			
		});
		es.shutdown();
	}
	public static void dirsCopy(String f1,String f2) throws Exception{
		BufferedInputStream bi;
		BufferedOutputStream bo;
		File[] files=new File(f1).listFiles();
		for(File file1: files) {
			File file2=new File(f2+"/"+file1.getName());
			if(file1.isFile()) {
				if(!file2.exists()) {
					file2.createNewFile();
				}
				bi=new BufferedInputStream(new FileInputStream(file1));
				bo=new BufferedOutputStream(new FileOutputStream(file2));
				byte[] b=new byte[1024];
				int n=0;
				while((n=bi.read(b))!=-1) {
					bo.write(b, 0, n);
				}
				bi.close();
				bo.close();
			}
			
			if(file1.isDirectory()) {
				if(!file2.exists()) {
					file2.mkdirs();
				}
				dirsCopy(file1.getPath(),f2+"/"+file1.getName());
			}
		}
	}
	
}